package com.bawey.vmusic;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.perm.kate.api.Auth;

public class AuthActivity extends Activity {

	public static final int REQUEST_LOGIN = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_auth);

		WebView loginView = (WebView) findViewById(R.id.loginForm);
		loginView.getSettings().setJavaScriptEnabled(true);
		loginView.clearCache(true);
		loginView.setWebViewClient(new VKViewClient());

		CookieSyncManager.createInstance(this);

		CookieManager.getInstance().removeAllCookie();

		loginView.loadUrl(Auth.getUrl(Globals.APP_ID, Auth.getSettings()));

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_auth, menu);
		return true;
	}

	class VKViewClient extends WebViewClient {
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			parseUrl(url);
		}
	}

	private void parseUrl(String url) {
		try {
			if (url == null)
				return;
			if (url.startsWith(Auth.redirect_url)) {
				if (!url.contains("error=")) {
					String[] auth = Auth.parseRedirectUrl(url);
					Intent intent = new Intent();
					intent.putExtra(Globals.KEY_TOKEN, auth[0]);
					intent.putExtra(Globals.KEY_USER_ID, Long.parseLong(auth[1]));
					setResult(Activity.RESULT_OK, intent);
				}
				finish();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
